package com.cems.controller;

import com.cems.pojo.SysAdmin;
import com.cems.pojo.SysAdminInfo;
import com.cems.pojo.SysEcharts;
import com.cems.pojo.UserShensu;
import com.cems.pojo.*;
import com.cems.service.AdminService;
import com.cems.service.UserService;
import com.cems.util.IDUtil;
import com.cems.util.LayuiReplay;
import com.cems.util.RedisUtil;
import com.cems.util.ShiroMd5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName AdminController
 * @Author 陈新予(blank)
 * @Date 2021/5/16
 * @Version 1.0
 */
@Controller
public class AdminController {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    AdminService adminService;
    @Autowired
    UserService userService;

    @GetMapping("isRes")
    public void isRes(String Num, String Pwd, String Pwd1, String Emil, String emilRes, HttpServletResponse resp) {
        try {
            PrintWriter out = resp.getWriter();
            if (Num.matches("^\\d*$")) {
                out.print("账号不能时纯数字!");
                return;
            }
            List<SysAdmin> admins = adminService.getAdmins();
            for (SysAdmin admin : admins) {
                if (admin.getAdminNum().equals(Num)) {
                    out.print("用户已存在!");
                    return;
                }
            }
            if (!Pwd.equals(Pwd1)) {
                out.print("两次密码不一致!");
                return;
            }
            String emilmsg = (String) redisUtil.get("cems" + Emil + "_msg");
            if (emilmsg.equals(emilRes)) {
                out.print("1");
            } else {
                out.print("验证码错误!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 管理员注册
    @PostMapping("resiger")
    public String Resiger(Model model, String Num, String Pwd, String Phone, String Emil) {
        HashMap<String, String> map = new HashMap<>();
        map.put("adminNum", Num);
        map.put("adminPwd", ShiroMd5Util.toPwdMd5(Num, Pwd));
        adminService.addAdmin(map, Num, Emil, Phone);
        model.addAttribute("msg", "注册成功");
        SysAdmin sysAdmin = adminService.selOneSysAdmin(Num);
        userService.insertSysSuc(sysAdmin.getId());
        return "back/adminLogin";
    }

    @GetMapping("sendAdminEmil")
    public void SendAdminEmil(String emil, HttpServletResponse rep) {
        PrintWriter out = null;
        try {
            out = rep.getWriter();
            if (emil == null || !emil.matches("^\\w+@\\w{2,6}\\.\\w{2,6}$")) {
                out.print("0");
                return;
            }
            String msg = IDUtil.getID().substring(0, 6);
            String title = "【验证码】";
            String text = "【CEMS校园服务平台】您的验证码为: " + msg + "，3分钟以内有效!";
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setSubject(title);
            mailMessage.setText(text);
            mailMessage.setTo(emil);
            mailMessage.setFrom("fcms_snut@qq.com");
            mailSender.send(mailMessage);
            try {
                redisUtil.set("cems" + emil + "_msg", msg);
                redisUtil.expire("cems" + emil + "_msg", 360, TimeUnit.SECONDS);
            } catch (Exception e) {
                out.print("0");
            }
            out.print("已发送");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @GetMapping("getalladmin")
    @ResponseBody
    public Object getAllAdmin(int page, int limit) {
        List<SysAdminInfo> admins = adminService.getAllAdminInfo();
        List<SysAdminInfo> userlimit = new ArrayList<>();
        for (int i = (page - 1) * limit; i < admins.size(); i++) {
            userlimit.add(admins.get(i));
            if (userlimit.size() == limit) {
                break;
            }
        }
        return new LayuiReplay<SysAdminInfo>(0, "OK", admins.size(), userlimit);
    }

    @RequestMapping("admin/toAdminCenter")
    public String ToAdminCenter() {
        return "back/adminCenter/adminInfo";
    }


    // 个人中心
    @RequestMapping("admin/getAdminInfo")
    @ResponseBody
    public SysAdminInfo getAdminInfo(HttpSession session) {
        SysAdmin admin = (SysAdmin) session.getAttribute("loginAdmin");
        return adminService.getAdminInfo(admin.getId());
    }

    @RequestMapping("admin/updateAdminInfo")
    @ResponseBody
    public String UpdateAdminInfo( @RequestBody SysAdminInfo admin) {
        try {
                adminService.updateAdminInfo(admin);
                return "更新成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "更新失败";
        }
    }

    @RequestMapping("admin/toChangePassword")
    public String ToChangePassword() {
        return "back/adminCenter/changePassword";
    }

    // 修改密码
    @RequestMapping("admin/changePassword")
    @ResponseBody
    public String changePassword(String newPwd, String oldPwd, HttpSession session) {
        try {
            SysAdmin admin = (SysAdmin) session.getAttribute("loginAdmin");

            System.out.println(admin.getAdminPwd()+"==="+ShiroMd5Util.toPwdMd5(admin.getAdminNum(), oldPwd));
            System.out.println(admin.getAdminPwd().equals(ShiroMd5Util.toPwdMd5(admin.getAdminNum(), oldPwd)));

            if (admin.getAdminPwd().equals(ShiroMd5Util.toPwdMd5(admin.getAdminNum(), oldPwd))) {
                adminService.changePassword(ShiroMd5Util.toPwdMd5(admin.getAdminNum(), newPwd), admin.getId());
                admin.setAdminPwd(ShiroMd5Util.toPwdMd5(admin.getAdminNum(), newPwd));
                session.setAttribute("loginName",admin);
            } else {
                return "旧密码不正确";
            }
            return "修改成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "修改失败";
        }
    }



    //处理用户后台账号申诉
    @GetMapping("admin/toshensu")
    public String shensu(){
        return "back/shensu/usershensu";
    }

    //获取申诉列表
    @RequestMapping("admin/findShensuList")
    @ResponseBody
    LayuiReplay findShensuList(int page,int limit){
        List<UserShensu> shensuList = adminService.findShensuList();
        return new LayuiReplay<UserShensu>(0, "OK", shensuList.size(), shensuList);
    }


    //解封
    @RequestMapping("admin/jiefeng")
    @ResponseBody
    public int jiefeng(String phone, HttpSession session){
        System.out.println(phone);
        try {
            adminService.jiefengUser(phone);
            return 0;
        }catch (Exception e){
            return 1;
        }finally {
            SysAdmin admin = (SysAdmin) session.getAttribute("loginAdmin");
            SysEcharts sys = userService.selOneSysSuc(admin.getId());
            Map<String,Object> map = new HashMap<>();
            map.put("adminId",admin.getId());
            map.put("loginNum",sys.getOperateNum()+1);
            userService.setSysLoginGraph(map);
        }
    }


    @ResponseBody
    @RequestMapping("adminshensucheck")
    public int shensucheck(String adminNum,String password){
        List<SysAdmin> sysAdmins = adminService.getAdmins();
        String pwd = ShiroMd5Util.toPwdMd5(adminNum,password);
        for (SysAdmin sysAdmin : sysAdmins) {
            if(sysAdmin.getAdminNum().equals(adminNum)){
                if(sysAdmin.getAdminPwd().equals(pwd)){
                    String status=adminService.findStatus(adminNum);
                    if (status.equals("正常")){
                        return 2;
                    }else {
                        return 0;
                    }
                }else {
                    return 1;
                }
            }
        }
        return 1;
    }


    //提交申诉
    @PostMapping("adminshensu")
    public String adminShensu(String adminNum,String content){
        adminService.adminShensu(adminNum,content);
        return "back/adminLogin";
    }


    //处理管理员 后台账号申诉
    @GetMapping("root/toshensu")
    public String toAdminshensu(){
        return "back/shensu/adminshensu";
    }



    //获取管理员申诉列表
    @RequestMapping("admin/findAdminShensuList")
    @ResponseBody
    LayuiReplay findAdminShensuList(int page,int limit){
        List<AdminShensu> adminShensuList = adminService.findAdminShensuList();
        return new LayuiReplay<AdminShensu>(0, "OK", adminShensuList.size(), adminShensuList);
    }



    //解封 管理员账号
    @RequestMapping("admin/jiefengAdmin")
    @ResponseBody
    public int jiefengAdmin(String adminNum){
        try {
            adminService.jiefengAdmin(adminNum);
            return 0;
        }catch (Exception e){
            return 1;
        }
    }


    //管理员找回密码
    @GetMapping("sendAdminEmilZhaohui")
    public void SendAdminEmilZhaohui(String emil, HttpServletResponse rep) {
        PrintWriter out = null;
        try {
            out = rep.getWriter();
            if (emil == null || !emil.matches("^\\w+@\\w{2,6}\\.\\w{2,6}$")) {
                out.print("0");
                return;
            }
            String msg = IDUtil.getID().substring(0, 6);
            String title = "【验证码】";
            String text = "【CEMS校园服务平台】您的验证码为" + msg + "，3分钟以内有效!";
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setSubject(title);
            mailMessage.setText(text);
            mailMessage.setTo(emil);
            mailMessage.setFrom("fcms_snut@qq.com");
            mailSender.send(mailMessage);
            try {
                redisUtil.set("cems" + emil + "_zhaohui", msg);
                redisUtil.expire("cems" + emil + "_zhaohui", 360, TimeUnit.SECONDS);
            } catch (Exception e) {
                out.print("0");
            }
            out.print("已发送");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("admin/zhaohui")
    public String zhaohuo(String adminNum,String newpwd1,String Emil,String emilRes){
        if (redisUtil.get("cems" + Emil + "_zhaohui")!=null){
            if (emilRes.equals(redisUtil.get("cems" + Emil + "_zhaohui"))){
                System.out.println(newpwd1);
                String newpwd = ShiroMd5Util.toPwdMd5(adminNum, newpwd1);
                adminService.zhaohuiAdmin(adminNum,newpwd);
            }
        }
        return "redirect:/toadminlogin";
    }


    @ResponseBody
    @RequestMapping("admin/zhaohuicheck")
    public int zhaohuicheck(String adminNum,String email){
        System.out.println(email);
       int res=adminService.zhaohuicheck(adminNum,email);
        if (res==0){
            return 0;
        }else {
            return 1;
        }
    }
}
